//
//  PaintingStyleCell.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/4.
//

import UIKit

class PaintingStyleCell: UITableViewCell {
    var dataSource:[PaintStyleListModel] = []
    var chooseStyleBag:( (Int) -> Void)?
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = Theme.color.main
        view.allRound(3)
        return view
    }()
    
    lazy var titleLb: UILabel = {
        let label = UILabel()
        label.font = UIFont.pingFangSCRegular(ofSize: 15)
        label.textColor = Theme.color.main
        label.text = "选择风格"
        return label
    }()
    lazy var collectionView: UICollectionView = {
        // 初始化 CustomFlowLayout
        let layout = CustomFlowLayout()
        // 初始化 UICollectionView 并设置 layout
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(cellWithClass: PaintingStyleItemCell.self)
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.addSubviews([lineView, titleLb, collectionView])
        
        lineView.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.leading.equalTo(16)
            make.width.equalTo(6)
            make.height.equalTo(16)
        }
        
        titleLb.snp.makeConstraints { make in
            make.centerY.equalTo(lineView)
            make.leading.equalTo(lineView.snp.trailing).offset(8)
        }
        
        var height = (SCREEN_WIDTH - 56) / 4
        height = height * 2 + 10
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(height)
        }
    }
    
    func setup(model:[PaintStyleListModel]?){
        guard let models = model else { return }
        self.dataSource = models
        if let model = Appearance.shared.recordStyle {
            if let index = self.dataSource.firstIndex(where: { $0.id == model.style_id } ) {
                self.dataSource[index].isSelect = true
            }
        }
        if let _ = self.dataSource.first(where: { $0.isSelect == true }) {
            // 如果已经有选中的项，不做任何操作
        } else {
            // 如果没有选中的项，默认选中第一个
            if !self.dataSource.isEmpty {
                self.dataSource[0].isSelect = true
            }
        }
        
        
        let totalItems = dataSource.count
        let remainder = totalItems % 2
        if remainder != 0 {
            let numberOfItemsToAdd = 2 - remainder
            for _ in 0..<numberOfItemsToAdd {
//                let emptyItem = PaintStyleListModel() // 创建空项目
//                dataSource.append(emptyItem)
            }
        }
        
        
        
        self.collectionView.reloadData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
extension PaintingStyleCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = self.dataSource[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withClass: PaintingStyleItemCell.self, for: indexPath)
        cell.coverIV.sd_setImage(with: URL(string: model.img_url ?? ""))
        cell.titleLb.text = (model.title ?? "").replacingOccurrences(of: "\n", with: "")
        
        cell.contentView.layer.borderWidth = 2
        if model.isSelect {
            cell.contentView.layer.borderColor = UIColor(hexString: "#45DFFF").cgColor
            cell.titleLb.backgroundColor = UIColor(hexString: "#45DFFF")
            cell.titleLb.textColor = Theme.color.text_d1
        }else {
            cell.contentView.layer.borderColor = UIColor.clear.cgColor
            cell.titleLb.backgroundColor = UIColor(hexString: "#222225", transparency: 0.9)
            cell.titleLb.textColor = .white
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (SCREEN_WIDTH - 56) / 4
        return CGSize(width: width, height: width)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        for (index, value) in dataSource.enumerated() {
            dataSource[index].isSelect = false
        }
        dataSource[indexPath.item].isSelect = true
        self.collectionView.reloadData()
        let model = self.dataSource[indexPath.item]

        self.chooseStyleBag?(model.id ?? 0)
    }
}
class CustomFlowLayout: UICollectionViewFlowLayout {
    var itemsPerRow: Int = 2 // 每行的项目数
    
    override func prepare() {
        super.prepare()
        guard let collectionView = collectionView else { return }
        
        // 设置 sectionInset, minimumLineSpacing 和 minimumInteritemSpacing
        sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        minimumLineSpacing = 10
        minimumInteritemSpacing = 10
        
        // 计算 item 的宽度和高度
        let itemWidth = (UIScreen.main.bounds.width - 16 - 16 - minimumInteritemSpacing * CGFloat(itemsPerRow - 1)) / CGFloat(itemsPerRow)
        let itemHeight = itemWidth // 根据设计设置高度
        itemSize = CGSize(width: itemWidth, height: itemHeight)
        
        // 设置滚动方向
        scrollDirection = .horizontal
    }
}
